<?php 
namespace app\system\admin;
use app\system\admin\Admin;
use think\Db;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

/**
 *  @author Lin
 *  @time 2021/7/22
 */
class Shop extends Admin
{
    protected function initialize()
    {
        parent::initialize();
        set_time_limit(0);
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $list = $this->getChilds(0);
            // var_dump($list);exit;
            $mylist[] = $list[0];
            $category = $this->getSelect($mylist);
            $this->assign('category', $category);
        }
    }

    function goods_type(){
        if ($this->request->isAjax()) {

            $where      = [];
            $list = Db::name('product_type')->where($where)->select();
            
            $data['data'] = $list;
            $data['count'] = Db::name('product_type')->where($where)->count('id');
            $data['code'] = 0;
            // var_dump($list);exit;
            return json($data);

        }
        return $this->fetch();
    }

    public function add(){
        if($this->request->isPost()){
            $list = $this->request->post();
            $type = $list['type'];
            unset($list['type']);
            // 新增分类
            if($type=='type'){
                $organ_check = Db::name('product_type')->where('id',$list['pid'])->value('pid');
                if($organ_check!=0&&$organ_check!=1){
                    return $this->error('分类暂不能超过3级');
                }
                $rs = Db::name("product_type")->insert($list);
                if($rs){
                    return $this->success('添加成功');
                }
                else{
                    return $this->error('添加失败，请重试');
                }
            }
             // 新增商品
            elseif($type=='goods'){
                // var_dump($list);exit;
                $spec = $list['spec'];
                unset($list['spec']);
                unset($list['id']);
                // if(!$spec['slcg_spec']){
                //     return $this->error('请录入采购送礼规格');
                // }
                if(!$list['unit_transform']){
                    return $this->error('请输入库存转化比');
                }

                // if(!$list['rest_num']){
                //     return $this->error('请输入商品库存');
                // }
                $list['price'] = implode(',',$spec['price']);
                $list['price_inner'] = implode(',',$spec['price_inner']);
                // $list['price_gift'] = implode(',',$spec['price_gift']);
                $list['spec_num'] = implode(',',$spec['spec_num']);
                $spec_num_check = array();
                foreach($spec['spec_num'] as $v){
                    if(in_array($v,$spec_num_check)){
                        return $this->error('规格数量不能重复');
                    }
                    $spec_num_check[] = $v;
                }
                
                $spec_name = '';
                $i = 0;
                $spec_list = array();
                foreach($spec['spec_unit'] as $key=>&$val){
                    if($i==0){
                        $spec_name = $val;
                    }
                    if($spec_name!=$val){
                        return $this->error('规格名称不能重复');
                    }
                    $i++;
                    if($spec['spec_num'][$key]==''){
                        $spec['spec_num'][$key] = 1;
                    }
                    if(!empty($val)){
                        $spec_list[] = $spec['spec_num'][$key].$val;
                    }
                    
                }
                $list['spec_unit'] = $spec['spec_unit'][0];
                $list['spec'] = implode(',',$spec_list);;
                
                $rs = Db::name("product")->insert($list);
                // var_dump($list);
                // return $this->error($rs);
                if($rs){
                    return $this->success('添加成功');
                }
                else{
                    return $this->error('添加失败，请重试');
                }
            }
            elseif($type=='pihao'){
                $in_data = array(
                    'name'=>$list['name'],
                    'goods_num'=>$list['goods_num'],
                    'pihao'=>$list['pihao'],
                    'num'=>$list['num'],
                    'ctime'=>time()
                );
                $pihao_check = Db::name('product_pihao')->where(array('pihao'=>$list['pihao'],'goods_num'=>$list['goods_num'],'name'=>$list['name']))->value('id');
                if($pihao_check){
                    $rs = Db::name('product_pihao')->where('id',$pihao_check)->setInc('num',$list['num']);
                }
                else{
                    $rs = Db::name('product_pihao')->insert($in_data);
                }
                if($rs){
                    return $this->success('操作成功');
                }
                else{
                    return $this->error('操作失败，请重试');
                }
            }
        }
        else{
            $type = input('type/s');
            $this->assign('type',$type);
            if($type=='type'){
                $template = $this->request->param('template', 'form');
            }
            elseif($type=='goods'){
                $template = $this->request->param('template', 'goods_form');
                $this->assign('li', '');
                $this->assign('spec', '');
                $banner = json_encode(array());
                $this->assign('banner',$banner);
            }
            elseif($type=='pihao'){
                $template = $this->request->param('template', 'pihao_form');
            }
            return $this->fetch($template);
        }
    }

    public function edit(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            // var_dump($list);exit;
            if(!$list['id']){
                return $this->error('参数错误');
            }
            else{
                $id = $list['id'];
                $type = $list['type'];
                unset($list['id']);
                unset($list['type']);
                if($type=='type'){
                    $rs = Db::name('product_type')->where('id',$id)->update($list);
                    if($rs){
                        return $this->success('更新成功');
                    }
                    else{
                        return $this->error('未修改任何信息');
                    }
                }
                elseif($type=='goods'){
                    $spec = $list['spec'];
                    unset($list['spec']);
                    // if(!$list['slcg_spec']){
                    //     return $this->error('请录入采购送礼规格');
                    // }
                    
                    if(!$list['unit_transform']){
                        return $this->error('请输入库存转化比');
                    }

                    // if(!$list['rest_num']){
                    //     return $this->error('请输入商品库存');
                    // }
                    $list['price'] = implode(',',$spec['price']);
                    $list['price_inner'] = implode(',',$spec['price_inner']);
                    // $list['price_gift'] = implode(',',$spec['price_gift']);
                    $list['spec_num'] = implode(',',$spec['spec_num']);
                    $spec_num_check = array();
                    foreach($spec['spec_num'] as $v){
                        if(in_array($v,$spec_num_check)){
                            return $this->error('规格数量不能重复');
                        }
                        $spec_num_check[] = $v;
                    }
                    
                    $spec_name = '';
                    $i = 0;
                    $spec_list = array();
                    foreach($spec['spec_unit'] as $key=>&$val){
                        if($i==0){
                            $spec_name = $val;
                        }
                        if($spec_name!=$val){
                            return $this->error('规格名称不能重复');
                        }
                        $i++;
                        if($spec['spec_num'][$key]==''){
                            $spec['spec_num'][$key] = 1;
                        }
                        if(!empty($val)){
                            $spec_list[] = $spec['spec_num'][$key].$val;
                        }
                    }
                    $list['spec_unit'] = $spec['spec_unit'][0];
                    $list['spec'] = implode(',',$spec_list);;
                    // if($list['slcg_price']&&(!$list['slcg_spec']||!$list['slcg_rest_num'])){
                    //     return $this->error('采购送礼参数设置不正确，必须全部设置或全部不设置');
                    // }
                    // if($list['slcg_spec']&&(!$list['slcg_price']||!$list['slcg_rest_num'])){
                    //     return $this->error('采购送礼参数设置不正确，必须全部设置或全部不设置');
                    // }
                    // if($list['slcg_rest_num']&&(!$list['slcg_price']||!$list['slcg_spec'])){
                    //     return $this->error('采购送礼参数设置不正确，必须全部设置或全部不设置');
                    // }
                    
                    $rs = Db::name("product")->where('id',$id)->update($list);
                    // var_dump($list);
                    // return $this->error($rs);
                    if($rs){
                        return $this->success('修改成功');
                    }
                    else{
                        file_put_contents('goods_upload_err.txt',json_encode($list));
                        file_put_contents('goods_upload_sql.txt',Db::name("product")->getLastSql());
                        return $this->error('修改失败，请重试');
                    }
                }
                elseif($type=='pihao'){
                    $up_data = array(
                        'name'=>$list['name'],
                        'goods_num'=>$list['goods_num'],
                        'pihao'=>$list['pihao'],
                        'num'=>$list['num'],
                        'ctime'=>time()
                    );
                    $rs = Db::name('product_pihao')->where('id',$id)->update($up_data);
                    if($rs){
                        return $this->success('更新成功');
                    }
                    else{
                        return $this->error('未修改任何信息');
                    }
                }
            }
        }
        $id = input("id/d");
        $type = input('get.type/s');
        if($type=="type"){
            $formData = Db::name("product_type")->where("id",$id)->find();
            $tmp = "form";
        }
        // 编辑商品
        elseif($type=="goods"){
            $formData = Db::name("product")->where("id",$id)->find();
            $li = '';
            if($formData['banner']){
                $banner_arr = explode(',',$formData['banner']);
                foreach($banner_arr as $key=>&$value){
                    $li .= '<img src="'.$value.'" height="100px" title="点击删除" class="layui-upload-img" onclick="delMultipleImgs(this)">';
                }
                $banner = $banner_arr;
                
            }
            else{
                $banner = array();
            }
            $banner = json_encode($banner);
            $this->assign('banner',$banner);
            $spec = '';
            if($formData['spec']){
                $spec_arr = explode(',',$formData['spec']);
                $price_arr = explode(',',$formData['price']);
                $price_inner_arr = explode(',',$formData['price_inner']);
                // $price_gift_arr = explode(',',$formData['price_gift']);
                $rest_num_arr = explode(',',$formData['rest_num']);
                $spec_num_arr = explode(',',$formData['spec_num']);
                $spec_unit = $formData['spec_unit'];
                foreach($spec_arr as $k=>&$v){
                    $spec .= '<div class="layui-form-item">'.
                    '<label class="layui-form-label"><span class="x-red">*</span>商品规格</label>'.
                    '<div class="layui-inline specname" >'.
                    ' <input type="text" id="" name="spec[spec_num][]" placeholder="数量"  autoComplete="off" class="layui-input" value="'.$spec_num_arr[$k].'">'.
                    '</div>'.
                    '<div class="layui-inline specname" >'.
                    ' <input type="text" id="" name="spec[spec_unit][]" placeholder="规格名称"  autoComplete="off" class="layui-input" value="'.$spec_unit.'">'.
                    '</div>'.
                    '<div class="layui-inline">'.
                    '<input type="text" name="spec[price][]" placeholder="该规格C端价格" autoComplete="off" class="layui-input" value="'.$price_arr[$k].'">'.
                    '</div>'.
                    '<div class="layui-inline">'.
                    '<input type="text" name="spec[price_inner][]" placeholder="该规格内购价格" autoComplete="off" class="layui-input" value="'.$price_inner_arr[$k].'">'.
                    '</div>'.
                    // '<div class="layui-inline">'.
                    // '<input type="text" name="spec[price_gift][]" placeholder="请输入该规格采购送礼价" lay-verify="required" autoComplete="off" class="layui-input" value="'.$price_gift_arr[$k].'">'.
                    // '</div>'.
                    // '<div class="layui-inline">'.
                    // '<input type="text" name="spec[rest_num][]" placeholder="请输入该规格库存" lay-verify="required" autoComplete="off" class="layui-input" value="'.$rest_num_arr[$k].'">'.
                    // '</div>'.
        
        
                    '<div class="layui-inline layui-show-xs-block"  style="margin-left: 45px;">'.
                    '<a class="layui-btn layui-btn-xs add">添加</a>'.
                    '<a class="layui-btn layui-btn-danger layui-btn-xs del">删除</a>'.
                    '</div>'.
                    '</div>';
                }
            }
            $this->assign('li', $li);
            $this->assign('spec', $spec);
            
            $tmp = "goods_form";

        }
        elseif($type=='pihao'){
            $tmp = "pihao_form";
            $formData = Db::name('product_pihao')->where('id',$id)->find();
        }
        $this->assign('formData', $formData);
        $this->assign('type', $type);
        $template = $this->request->param('template', $tmp);
        return $this->fetch($template);
    }

    function pihao(){
        if ($this->request->isAjax()) {
            $gwhere = [];
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $keyword = input('keyword');
            if($keyword){
                $where[] = ['name','like',"%".$keyword."%"];
                $where[] = ['pihao','like',"%".$keyword."%"];
            }
            
            $list = Db::name('product_pihao')->whereOR($where)->where($gwhere)->page($page)->limit($limit)->order('id desc')->select();
            foreach($list as $key=>&$value){
                $value['ctime'] = $value['ctime']?date('Y-m-d H:i:s',$value['ctime']):'';
                $value['user_num'] = Db::name('orders')->where('pihao',$value['id'])->sum('pihao_num');
            }
            // $sql = Db::name('product')->getLastSql();
            // echo $sql;exit;
            $data['data'] = $list;
            $data['count'] = Db::name('product_pihao')->whereOR($where)->where($gwhere)->count('id');
            $data['code'] = 0;
            return json($data);

        }
        return $this->fetch();
    }
    function upload(){
        $file = request()->file('file');
        $info = $file->move(ROOT_PATH.'public/upload');
        // var_dump($info);exit;
        if($info) {
            $data['code'] = 0;
            $data['msg'] = $info->getSaveName();
            $data['type'] = $info->getExtension();//获取图片的类型
            $file_info = $info->getInfo();
            if($data['type'] == 'jpg' || $data['type'] == 'gif' || $data['type'] == 'png' || $data['type'] == 'jpeg'){
                Db::name('files')->insert([
                    'pic' => 'upload/'.$data['msg'],
                    'name'=>$file_info['name'],
                    'size'=>sprintf('%.2f',$file_info['size']/1024/1024)."M",
                    'type'=>$data['type'],
                    'ctime' => time()
                ]);
                return $this->success('提交成功');
            }
        }else{
            return $this->error('提交失败，请重试');
        }
    }

    function del(){
        $id = input("get.id/d");
        $type = input('get.type/s');
        // 删除类型
        if($type=='type'){
            if($id==0){
                return $this->error('总分类不能删除');
            }
            $rs = Db::name('product_type')->where('id',$id)->delete();
            if($rs){
                return $this->success('删除成功');
            }
            else{
                return $this->error('删除失败，请重试');
            }
        }
        elseif($type=="goods"){
            $rs = Db::name('product')->where('id',$id)->delete();
            if($rs){
                Db::name('product_jifen')->where('pid',$id)->delete();
                return $this->success('删除成功');
            }
            else{
                return $this->error('删除失败，请重试');
            }
        }
        elseif($type=='pihao'){
            $rs = Db::name('product_pihao')->where('id',$id)->delete();
            if($rs){
                return $this->success('删除成功');
            }
            else{
                return $this->error('删除失败，请重试');
            }
        }
        
    }


    // 将数据集整理成父子结构
    public function getChilds($pid = 1, $data = []){
        $trees = [];
        if (empty($data)) {
            $map = [];
            $data = Db::name('product_type')->where($map)->select();
            $data = array_values($data); 
        }

        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                unset($data[$k]);
                
                if(!empty($data)){
                    $v['childs'] = $this->getChilds($v['id'], $data);
                }
                
                $trees[] = $v;
            
                // continue;
            }   
        }
        return $trees;
    }
    // 获取选择器数据集
    public function getSelect($data = [], $id = 0, $level = 0){
        if (empty($data)) {
            return '';
        }
        $str = $separ = '';
        if ($level > 0) {
            for ($i=0; $i < $level; $i++) {
                $separ .= '&nbsp;&nbsp;&nbsp;';
            }
            $separ .= '┣&nbsp;';
        }

        foreach ($data as $k => $v) {
            if ($id == $v['id']) {
                $str .= '<option value="'.$v['id'].'" selected>'.$separ.$v['name'].'</option>';
            } else {
                $str .= '<option value="'.$v['id'].'">'.$separ.$v['name'].'</option>';
            }
            if (isset($v['childs'])) {
                $str.= $this->getSelect($v['childs'], $id, $level+1);
            }
        }
        return $str;
    }

    function goods(){
        // 产品分类
        $gwhere = [];
        $groups = Db::name('product_type')->where($gwhere)->column('id,name');
        
        $this->assign('groups', $groups);

        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $keyword = input('keyword');
            if($keyword){
                $where[] = ['name','like',"%".$keyword."%"];
                $where[] = ['sub_name','like',"%".$keyword."%"];
            }
            $group_id = input('group_id');
            $gwhere = [];
            if($group_id&&$group_id!=1){
                $child_check = Db::name('product_type')->where('pid',$group_id)->field('id')->select();
                if(!$child_check){
                    $gwhere[] = ['type_id','eq',$group_id];
                }
                // $where['type_id'] = $group_id;
            }
            
            $list = Db::name('product')->whereOR($where)->where($gwhere)->page($page)->limit($limit)->order('id desc')->select();
            foreach($list as $key=>&$value){
                if($value['price']){
                    $price_arr = explode(',',$value['price']);
                    $value['price'] = $price_arr[0];
                }
                $value['link'] = '/pages/productDetails/productDetails?id='.$value['id'];

                if($value['rest_num']<=$value['rest_num_notify']&&$value['rest_num_notify']>0){
                    $value['need_notify'] = 1;
                }
                else{
                    $value['need_notify'] = 0;
                }
            }
            // $sql = Db::name('product')->getLastSql();
            // echo $sql;exit;
            $data['data'] = $list;
            $data['count'] = Db::name('product')->whereOR($where)->where($gwhere)->count('id');
            $data['code'] = 0;
            return json($data);

        }
        return $this->fetch();
    }

    // 分销商设置
    function fx_user(){
        // 产品分类
        $gwhere = [];
        // $groups = Db::name('product_type')->where($gwhere)->column('id,name');

        // $this->assign('groups', $groups);

        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $keyword = input('keyword');
            if($keyword){
                $where[] = ['nickname','like',"%".$keyword."%"];
                $where[] = ['phone','like',"%".$keyword."%"];
            }
            $group_id = input('group_id');
            $gwhere = [];
            if($group_id>0){
                $gwhere[] = ['level','eq',$group_id];
                // $where['type_id'] = $group_id;
            }
            if($group_id==-1){
                $gwhere[] = ['is_partner','eq',0];
            }
            
            $list = Db::name('user')->whereOR($where)->where($gwhere)->page($page)->limit($limit)->select();
            foreach($list as $key=>&$value){
                if($value['is_partner']){
                    $value['is_partners'] = '是';
                }
                else{
                    $value['is_partners'] = '否';
                }

                if($value['level']>0){
                    $value['level'] = $value['level']."级分销商";
                }
                else{
                    $value['level'] = '';
                }

                $value['ctime'] = $value['ctime']>0?date('Y-m-d H:i:s',$value['ctime']):'';
            }
            // $sql = Db::name('product')->getLastSql();
            // echo $sql;exit;
            $data['data'] = $list;
            $data['count'] = Db::name('user')->whereOR($where)->where($gwhere)->count('id');
            $data['code'] = 0;
            return json($data);

        }
        return $this->fetch();
    }

    function status(){
        $id = input('id/d');
        $type=input('type');
        if($type=='is_partner'){
            $is_partner = Db::name('user')->where('id',$id)->value('is_partner');
            if($is_partner==0){
                $is_partner = -1;
            }
            else{
                $is_partner = 0;
            }
            $rs = Db::name('user')->where('id',$id)->update(array('is_partner'=>$is_partner));
        }
        else{
            $status = Db::name('user')->where('id',$id)->value('status');
            if($status==0){
                $status = -1;
            }
            else{
                $status = 0;
            }
            $rs = Db::name('user')->where('id',$id)->update(array('status'=>$status));
        }

        if($rs){
            return $this->success('操作成功');
        }
        else{
            return $this->error('操作失败，请重试');
        }
        
    }

    public function fx_edit(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            // var_dump($list);exit;
            if(!$list['id']){
                return $this->error('参数错误');
            }
            else{
                $id = $list['id'];
                unset($list['id']);
                unset($list['nickname']);
                if($list['level']>0){
                    $list['is_partner'] = 1;
                }
                $rs = Db::name('user')->where('id',$id)->update($list);
                if($rs){
                    return $this->success('修改成功');
                }
                else{
                    return $this->error('修改失败，请重试');
                }
            }
        }
        $id = input("id/d");
        $formData = Db::name('user')->where('id',$id)->find();
        $this->assign('formData', $formData);
        $template = $this->request->param('template', 'fx_user_form');
        return $this->fetch($template);
    }

    // 分销商品设置
    function fx_goods(){
        // 产品分类
        $gwhere = [];
        $groups = Db::name('product_type')->where($gwhere)->column('id,name');

        $this->assign('groups', $groups);

        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $keyword = input('keyword');
            if($keyword){
                $where[] = ['name','like',"%".$keyword."%"];
                $where[] = ['sub_name','like',"%".$keyword."%"];
            }
            $group_id = input('group_id');
            $gwhere = [];
            if($group_id&&$group_id!=1){
                $child_check = Db::name('product_type')->where('pid',$group_id)->field('id')->select();
                if(!$child_check){
                    $gwhere[] = ['type_id','eq',$group_id];
                }
                // $where['type_id'] = $group_id;
            }
            
            $list = Db::name('product')->whereOR($where)->where($gwhere)->page($page)->limit($limit)->order('id desc')->select();
            
            // $sql = Db::name('product')->getLastSql();
            // echo $sql;exit;
            $data['data'] = $list;
            $data['count'] = Db::name('product')->whereOR($where)->where($gwhere)->count('id');
            $data['code'] = 0;
            return json($data);

        }
        return $this->fetch();
    }

    // 参与/不参与分销
    function is_fenxiao(){
        $id = input('id/d');
        $is_fenxiao = Db::name('product')->where('id',$id)->value('is_fenxiao');
        if($is_fenxiao==0){
            $is_fenxiao = 1;
        }
        else{
            $is_fenxiao = 0;
        }
        $rs = Db::name('product')->where('id',$id)->update(array('is_fenxiao'=>$is_fenxiao));
        if($rs){
            return $this->success('操作成功');
        }
        else{
            return $this->error('操作失败，请重试');
        }
    }

    public function fx_goods_edit(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            // var_dump($list);exit;
            if(!$list['id']){
                return $this->error('参数错误');
            }
            else{
                $id = $list['id'];
                unset($list['id']);
                unset($list['name']);
                unset($list['sub_name']);
                
                $rs = Db::name('product')->where('id',$id)->update($list);
                if($rs){
                    return $this->success('修改成功');
                }
                else{
                    return $this->error('修改失败，请重试');
                }
            }
        }
        $id = input("id/d");
        $formData = Db::name('product')->where('id',$id)->find();
        $this->assign('formData', $formData);
        $fx_init_rule = Db::name('fenxiao_init_rule')->where('id',1)->find();
        $this->assign('fx_init_rule', $fx_init_rule);
        $template = $this->request->param('template', 'fx_goods_form');
        return $this->fetch($template);
    }

    // 分销默认设置
    function fenxiao(){
        if ($this->request->isAjax()) {
            $where      = [];
            
            
            $list = Db::name('fenxiao_init_rule')->where('id',1)->select();
            
            // $sql = Db::name('product')->getLastSql();
            // echo $sql;exit;
            $data['data'] = $list;
            $data['count'] = Db::name('fenxiao_init_rule')->where('id',1)->count('id');
            $data['code'] = 0;
            return json($data);

        }
        return $this->fetch();
    }

    // 修改默认分成比例
    function changePercent(){
        $val = input('val');
        $field = input('field/s');
        $id = input('id/d');
        // $where[] = ['id','eq',$id];
        $where['id'] = $id;
        $data["$field"] = $val;
        // $data[] = [$field,'eq',$val];
        $rs = Db::name('fenxiao_init_rule')->where($where)->update($data);
        if($rs){
            okMsg();
        }
        else{
            errMsg('提交失败');
        }
    }

    // 评论管理
    function consumes(){
        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            
            $list = Db::name('product_consume')->alias('a')->join('user b','a.uid=b.id','left')->join('product c','a.pid=c.id','left')->order('ctime desc')->page($page)->limit($limit)->field('a.*,b.nickname,b.headimg,c.name,c.share_img')->select();
            
            if($list){
                foreach($list as &$value){
                    $value['ctime'] = $value['ctime']?date('Y-m-d H:i:s',$value['ctime']):'';
                }
            }
            // $sql = Db::name('product')->getLastSql();
            // echo $sql;exit;
            $data['data'] = $list;
            $data['count'] = Db::name('product_consume')->count('id');
            $data['code'] = 0;
            return json($data);
        }
        return $this->fetch();
    }

    function consume_status(){
        $id = input('id/d');
        $status = Db::name('product_consume')->where('id',$id)->value('status');
        if($status==0){
            $status = 1;
        }
        else{
            $status = 0;
        }
        $rs = Db::name('product_consume')->where('id',$id)->update(array('status'=>$status));
        if($rs){
            return $this->success('操作成功');
        }
        else{
            return $this->error('操作失败，请重试');
        }
    }

    function del_consume(){
        $id = input('id/d');
        $rs = Db::name('product_consume')->where('id',$id)->delete();
        if($rs){
            return $this->success('删除成功');
        }
        else{
            return $this->error('删除失败，请重试');
        }
    }

    function edit_consume(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            // var_dump($list);exit;
            $list['ctime'] = time();
            if(!$list['id']){
                return $this->error('参数错误');
            }
            else{
                $id = $list['id'];
                unset($list['id']);
                unset($list['name']);
                $rs = Db::name("product_consume")->where('id',$id)->update($list);
                // var_dump($list);
                // return $this->error($rs);
                if($rs){
                    return $this->success('修改成功');
                }
                else{
                    return $this->error('修改失败，请重试');
                }
            }
        }
        $id = input("id/d");
        $formData = Db::name("product_consume")->alias('a')->join('user b','a.uid=b.id','left')->join('product c','a.pid=c.id','left')->where("a.id",$id)->order('ctime desc')->field('a.*,b.nickname,b.headimg,c.name,c.share_img')->find();
        $this->assign('formData', $formData);
        $template = $this->request->param('template', 'consume_form');
        return $this->fetch($template);
    }

    function add_in(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            $list['ctime'] = time();
            if($list['in_num']>0){
                $rs = Db::name('product_in_record')->insert($list);
                if($rs){
                    Db::name('product')->where('id',$list['pid'])->setInc('all_in_num',$list['in_num']);
                    return $this->success('操作成功');
                }
                else{
                    return $this->error('操作失败，请重试');
                }
            }
            else{

            }
        }
        $id = input('id/d');
        // $list = Db::name('product_in_record')->where('pid',$id)->order('ctime desc')->select();
        $this->assign('pid',$id);
        $template = $this->request->param('template', 'add_in_form');
        return $this->fetch($template);
    }

    function getList(){
        $id = input('id');
        $list = Db::name('product_in_record')->where('pid',$id)->order('ctime desc')->select();
        if($list){
            foreach($list as &$value){
                $value['ctime'] = $value['ctime']?date('Y-m-d H:i:s',$value['ctime']):'';
            }
        }
        $data['data'] = $list;
        $data['count'] = Db::name('product_in_record')->where('pid',$id)->count('id');
        $data['code'] = 0;
        return json($data);
    }

    // 检测库存是否需要弹出预警
    function kucun(){
        // echo ADMIN_ID;exit;
        $is_per = session('is_per');
        $user = session('admin_user');
        if(!$is_per){
            $role_id = $user['role_id'];
            if($role_id>1){
                $auth = Db::name('system_role')->where('id',$role_id)->value('auth');
                $auth_arr = json_decode($auth,true);
                if(in_array(145,$auth_arr)){
                    $is_per = 1;
                }
                else{
                    $is_per = -1;
                }
            }
            else{
                $is_per = 1;
            }
            session('is_per',$is_per);
        }
        
        if($is_per==1){
            $where[] = ['rest_num_notify','gt',0];
            $where[] = ['rest_num','elt','`rest_num_notify`'];
            $where[] = ['status','eq',1];
            $list = Db::name('product')->where($where)->field('id,name')->select();
            if($list){
                // Db::name()

                $content = "您的产品";
                $pids = array();
                foreach($list as &$value){
                    $content .= $value['name']."、";
                    $pids[] = $value['id'];
                }
                $pid_str = implode(',',$pids);
                // $content = substr($content,0,strlen($content)-1);
                

                $day = date('Y-m-d',time());
                $dwhere[] = ['day','eq',$day];
                $dwhere[] = ['uid','eq',ADMIN_ID];
                $dwhere[] = ['pids','eq',$pid_str];
                $notify_record = Db::name('notify_record')->where($dwhere)->find();

                if(!$notify_record){
                    $content .= '库存已超预警，请尽快补充库存';

                    // var_dump($content);exit;

                    $data['data'] = $content;
                    $data['error'] = 200;
                    $data = serialize($data);
                    $data = mb_convert_encoding($data, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
                    $data = unserialize($data);


                    $in_data = array(
                        'uid'=>ADMIN_ID,
                        'day'=>$day,
                        'notify_times'=>1,
                        'pids'=>$pid_str,
                        'ctime'=>time()
                    );
                    Db::name('notify_record')->insert($in_data);
                    return json($data);
                }
                
            }
            else{
                $data['data'] = '无预警信息';
                $data['error'] = 0;
                $data = serialize($data);
                $data = mb_convert_encoding($data, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
                $data = unserialize($data);
                return json($data);
            }

            
            // var_dump(Db::name('product')->getLastSql());
        }
        else{
            $data['data'] = '无预警信息';
            $data['error'] = 0;
            $data = serialize($data);
            $data = mb_convert_encoding($data, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
            $data = unserialize($data);
            return json($data);
        }
        // var_dump(json_decode($auth,true));
        // var_dump($user);exit;
        // var_dump(session('role_auth_'));exit;
    }
}

?>